package com.hanson.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hanson.Const;
import com.hanson.common.exception.BusinessException;
import com.hanson.common.service.RedisService;
import com.hanson.entity.GoodsBean;
import com.hanson.entity.IndexSlideBean;
import com.hanson.mapper.GoodsBeanMapper;
import com.hanson.mapper.IndexSlideBeanMapper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@CacheConfig(cacheNames = "SlideData")
public class IndexSlideService {
    @Autowired
    private IndexSlideBeanMapper indexSlideBeanMapper;
    @Autowired
    private GoodsBeanMapper goodsBeanMapper;
    @Autowired
    private RedisService redisService;

    public void add(IndexSlideBean indexSlideBean) {
        check(indexSlideBean);
        indexSlideBean.setCreateDate(new Date());
        indexSlideBeanMapper.insert(indexSlideBean);
        redisService.del(Const.SLIDE_REDIS_KEY);
    }

    public void modify(IndexSlideBean indexSlideBean) {
        check(indexSlideBean);
        IndexSlideBean returnBean = indexSlideBeanMapper.selectByPrimaryKey(indexSlideBean.getId());
        if (null != returnBean) {
            indexSlideBean.setCreateDate(returnBean.getCreateDate());
            indexSlideBeanMapper.updateByPrimaryKey(indexSlideBean);
            redisService.del(Const.SLIDE_REDIS_KEY);
        }
    }

    private void check(IndexSlideBean indexSlideBean) {
        if (null == indexSlideBean.getGoodsId() && StringUtils.isEmpty(indexSlideBean.getVideo())) {
            throw new BusinessException("商品或视频必须选一个");
        }
    }

    public void delete(Integer id) {
        indexSlideBeanMapper.deleteByPrimaryKey(id);
        redisService.del(Const.SLIDE_REDIS_KEY);
    }

    public IndexSlideBean detail(Integer id) {
        IndexSlideBean indexSlideBean = indexSlideBeanMapper.selectByPrimaryKey(id);
        if (null != indexSlideBean && indexSlideBean.getGoodsId() != null) {
            GoodsBean goodsBean = goodsBeanMapper.selectByPrimaryKey(indexSlideBean.getGoodsId());
            if (null != goodsBean) {
                indexSlideBean.setGoodsImage(goodsBean.getImage());
            }
        }
        return indexSlideBean;
    }

    @Cacheable(key = "'selectAll'", unless = "#result == null")
    public List<IndexSlideBean> selectAll() {
        return indexSlideBeanMapper.selectAll();
    }

    public Page<IndexSlideBean> listIndexSlides(Page<IndexSlideBean> page, IndexSlideBean indexSlideBean) {
        List<IndexSlideBean> list = indexSlideBeanMapper.listIndexSlides(page, indexSlideBean);
        return page.setRecords(list);
    }
}
